package com.flyox.game.fivetiger.bean;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Iterator;
import java.util.Stack;
import java.util.Timer;
import java.util.TimerTask;

import com.flyox.game.fivetiger.control.FivetigerControl;

/**
 * 播放下棋过程
 * 
 * @author sunwei
 * 
 */
public class LayoutPlayer {
	private FivetigerControl control;
	private Stack stepts;
	private final Timer timer = new Timer();

	public LayoutPlayer(final FivetigerControl control) {
		this.control = control;
		ObjectInputStream oos = null;
		try {
//			String path = LayoutPlayer.class.getResource("/").toString();
//			path = path.substring(path.indexOf("/") + 1);
//			path += "/com/flyox/game/fivetiger/res/chess.fcs";
			
			oos = new ObjectInputStream(getClass().getClassLoader().getResourceAsStream("com/flyox/game/fivetiger/res/chess.fcs"));
			stepts = (Stack) oos.readObject();
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		} finally {
			try {
				oos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void play() {
		final Iterator it = stepts.iterator();
		TimerTask task = new TimerTask() {
			public void run() {
				if (!it.hasNext()) {
					stop();
				} else {
					MsgPackage msg = (MsgPackage) it.next();
					control.play(msg);
				}
			}
		};
		timer.schedule(task, 0, 1000);
	}

	public void stop() {
		timer.cancel();
		control.getDoc().reInit();
		control.getView().jButtonCreate.setEnabled(true);
		control.getView().jComboBoxIP.setEnabled(true);
	}
}
